package com.jyx.user.service.impl;

import com.jyx.user.exception.UserExistException;
import com.jyx.user.mapper.TMemberMapper;
import com.jyx.user.pojo.TMember;
import com.jyx.user.pojo.TMemberExample;
import com.jyx.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired(required = false)
    private TMemberMapper memberMapper;

    @Override
    //用户注册
    public void registerUser(TMember member) {
        //查询当前手机号是否已经注册
        TMemberExample memberExample = new TMemberExample();
        TMemberExample.Criteria criteria = memberExample.createCriteria();
        criteria.andLoginacctEqualTo(member.getLoginacct());
        List<TMember> members = memberMapper.selectByExample(memberExample);
        //如果已被注册,抛出异常
        if (members != null && members.size() > 0){
            throw new UserExistException();
        }
        //密码加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String pswd = encoder.encode(member.getUserpswd());
        member.setUserpswd(pswd);
        //设置未认证
        member.setAuthstatus("0");
        //设置个人类型的用户
        member.setUsertype("0");
        //设置个人账户
        member.setAccttype("2");
        memberMapper.insert(member);
    }

    @Override
    //用户登录
    public TMember login(String loginacct, String userpswd) {
        //根据loginacct查询TMember
        TMemberExample example = new TMemberExample();
        TMemberExample.Criteria criteria = example.createCriteria();
        criteria.andLoginacctEqualTo(loginacct);
        List<TMember> members = memberMapper.selectByExample(example);
        //判断是否存在此用户并且密码相同
        if (members != null && members.size() > 0){
            String userpswd1 = members.get(0).getUserpswd();
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(userpswd, userpswd1);
            return matches ? members.get(0) : null;
        }
        return null;
    }

    @Override
    public TMember findTMemberById(Integer id) {
        TMember member = memberMapper.selectByPrimaryKey(id);
        return member;
    }
}
